﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Evan.Template
{
    /// <summary>
    /// 生成静态页 每次生成一个页面
    /// </summary>
    public static class CreateStaticPage
    {
        /// <summary>
        /// 获取静态页的底部申明和信息
        /// </summary>
        /// <returns></returns>
        public static string GetPagePowerBy() { return string.Format("\r\n<!-- Powered by szweb.cn (SmartaCMS)   PublishDate {0}-->", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); }

        /// <summary>
        /// 获取URL列表
        /// </summary>
        /// <param name="ChannelId"></param>
        /// <returns></returns>
        public static List<string> GetUrlList(int ChannelId=0)
        {
            if (ChannelId == 0)
            {
                return new Evan.Template.Base().GetUrlList();
            }
            else
            {
                return new Evan.Template.Base().GetUrlList(ChannelId);
            }   
        }



        /// <summary>
        /// HTTP GET方式请求数据.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <returns></returns>
        private static string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "*/*";
            request.Headers.Add("CreateStaticPage","1"); //加入请求头文件 , 标识是请求生成静态页
            request.Timeout = 10000; //10秒超时时间
            request.AllowAutoRedirect = false;
            HttpWebResponse response = null;
            string responseStr = "";

            try
            {
                response = request.GetResponse() as HttpWebResponse;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //如果响应状态码是正常码
                    if (response != null)
                    {

                        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        responseStr = reader.ReadToEnd();
                        reader.Close();
                    }
                    else {
                        Evan.SystemLog.MemLog.AddExLog2("生成静态页的地址响应为空", null, "请求地址 " + url + " ,  响应为空 , 响应状态说明 : " + response.StatusDescription);
                    }
                }
                else
                {
                    //响应状态码不正常的时候
                    Evan.SystemLog.MemLog.AddExLog2("生成静态页的地址响应出错", null, "请求地址 "+url+" ,  响应出错 , 响应状态说明 : " + response.StatusDescription);
                }
            }
            catch (WebException ex)
            {
                //请求出错
                var rsp = ex.Response as HttpWebResponse;
                Evan.SystemLog.MemLog.AddExLog2("生成静态页的地址请求出错", null, "请求地址 " + url + " ,  请求出错 , 响应状态说明 : " + rsp.StatusDescription);
            }
            finally
            {
                request = null;
                response = null;
            }

            return responseStr;
        }

        private static void CreateDir(string dir)
        {
            if (dir.Length == 0) return;
            if (!System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(dir));
        }
        private static string GetFolderPath(bool isUrl, string filePath)
        {
            if (isUrl)
                return filePath.Substring(0, filePath.LastIndexOf("/") + 1);
            else
                return filePath.Substring(0, filePath.LastIndexOf("\\") + 1);
        }
        /// <summary>
        /// 保存文件内容,自动创建目录
        /// </summary>
        /// <param name="TxtStr"></param>
        /// <param name="tempDir">格式:a/b.htm,相对根目录</param>
        /// <param name="noBom"></param>
        private static void SaveFile(string TxtStr, string tempDir, bool noBom)
        {
            try
            {
                CreateDir(GetFolderPath(true, tempDir));
                System.IO.StreamWriter sw;
                if (noBom)
                {
                    sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath(tempDir), false, new System.Text.UTF8Encoding(false));
                }
                else
                {
                    sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath(tempDir), false, System.Text.Encoding.UTF8);
                }
                TxtStr = TxtStr + GetPagePowerBy();
                sw.Write(TxtStr);
                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 生成页面
        /// </summary>
        /// <param name="WebUrl">网站地址 , http://a.com </param>
        /// <param name="Url">页面地址 , /news/1.html</param>
        /// <param name="FilePath">需要生成到的页面地址 默认为空 , 如果有指定 生成到指定目录</param>
        /// <returns></returns>
        public static bool Create(string WebUrl, string Url, string FilePath = "")
        {
            try
            {
                //先删除原来的静态页
                string Old_Path = (string.IsNullOrEmpty(FilePath) ? "" : "/" + FilePath) + Url;
                Old_Path = System.Web.HttpContext.Current.Server.MapPath("~" + Old_Path);
                if (System.IO.File.Exists(Old_Path))
                {
                    //文件存在则删除
                    System.IO.File.Delete(Old_Path);
                }

                string RequestUrl = WebUrl.TrimEnd('/') + Url;
                //请求上面的地址
                //拿到返回数据 , 保存到FilePath
                string responseStr = HttpGet(RequestUrl);
                if (!string.IsNullOrEmpty(responseStr))
                {
                    if (string.IsNullOrEmpty(FilePath))
                    {
                        SaveFile(responseStr, Url, true);
                    }
                    else
                    {
                        SaveFile(responseStr, "/" + FilePath + Url, true);
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                SystemLog.MemLog.AddExLog2("生成页面失败", null, ex.ToString());
                return false;
            }
        }

    }
}
